'use strict';

const sqlite3 = require('sqlite3').verbose();
const db = new sqlite3.Database('/home/yami/ygowiki-server/cards.cdb');

const getData = function(id) {
  return new Promise((resolve, reject) => {
    let res = {};

    db.get("SELECT name, desc from texts where id='" + id + "'", function (err, row) {
      if (err) {
        reject(err);
        return;
      } else {
        res = Object.assign(res, row);
      }      
    });

    db.get("SELECT id, atk, def, race, type, level, attribute from datas where id='" + id + "'", function (err, row) {
      if (err) {
        reject(err);
        return;
      } else {
        res = Object.assign(res, row);
        resolve(res);
      }      
    });
  })
}


const getMultiData = function(ids) {
  if (typeof ids === 'string') ids = JSON.parse(ids);

  const promiseList = ids.map((id, index) => {
    return new Promise((resolve, reject) => {
      getData(id)
        .then(data => resolve(data))
        .catch(err => reject(err));
    });
  });

  return Promise.all(promiseList);
}

const walkData = async function* () {
  let index = 0;

  const getDataByIndex = () => {
    return new Promise((resolve, reject) => {
      let res = {};

      db.get(`SELECT name, desc from texts limit 1 offset ${index}`, function (err, row) {
        if (err) {
          reject(false);
          return;
        } else {
          res = Object.assign(res, row);
        }      
      });
  
      db.get(`SELECT id, atk, def, race, type, level, attribute from datas limit 1 offset ${index}`, function (err, row) {
        if (err) {
          reject(false);
          return;
        } else {
          res = Object.assign(res, row);
          index += 1;
          resolve(res);
        }      
      });
    });
  };

  while (true) {
    yield getDataByIndex();
  }
};

module.exports = {
  getData,
  getMultiData,
  walkData,
};
